package com.fg.room.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fg.common.entity.Dto.UserDto;
import com.fg.common.response.R;
import com.fg.common.util.Assert;
import com.fg.common.valid.AddStrategy;
import com.fg.common.valid.UpdateStrategy;
import com.fg.room.enums.DeviceScrapStatus;
import com.fg.room.listener.RoomDeviceInfoDocListener;
import com.fg.room.pojo.DO.*;
import com.fg.room.pojo.DTO.DeviceInfoDto;
import com.fg.room.pojo.DTO.DeviceInfoPageQueryDto;
import com.fg.room.pojo.VO.AddressInfoVo;
import com.fg.room.service.AddressInfoService;
import com.fg.room.service.BrandInfoService;
import com.fg.room.service.DeviceInfoService;
import com.fg.room.service.DeviceTypeService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理 控制层
 * </p>
 *
 * @author ct
 * @since 2021-04-26
 **/
@RestController
@RequestMapping("/web/device")
@Api(tags = "设备管理")
@AllArgsConstructor
public class DeviceInfoController {

    private final AddressInfoService addressService;
    private final DeviceInfoService deviceInfoService;
    private final BrandInfoService brandInfoService;
    private final DeviceTypeService deviceTypeService;

    @GetMapping("/download")
    @ApiOperation("设备管理excel表格下载")
    @ApiOperationSupport(order = 1)
    public void download(HttpServletResponse response) throws IOException {
        InputStream inputStream = DeviceInfoController.class.getClassLoader().getResourceAsStream("templet/设备管理.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        String fileName = new String("设备管理".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        IOUtils.copy(inputStream, outputStream);
    }

    @PostMapping("/upload")
    @ApiOperation("设备管理excel表格批量导入")
    @ApiOperationSupport(order = 2)
    public R upload(MultipartFile file) throws IOException {
        Assert.assertNotNull(file, "上传的文件不能为空！");
        //获取所有品牌名称
        List<BrandInfoDo> brandInfoDoList = brandInfoService
                .list(Wrappers.<BrandInfoDo>lambdaQuery().select(BrandInfoDo::getName, BrandInfoDo::getId));
        //获取所有设备类型名称
        List<DeviceTypeDo> deviceTypeDoList = deviceTypeService
                .list(Wrappers.<DeviceTypeDo>lambdaQuery().select(DeviceTypeDo::getName, DeviceTypeDo::getId));
        //获取所有地址名称
        List<AddressInfoDo> addressInfoDoList = addressService
                .list(Wrappers.<AddressInfoDo>lambdaQuery().select(AddressInfoDo::getName, AddressInfoDo::getId));
        UserDto userDto = (UserDto) SecurityUtils.getSubject().getPrincipal();
        EasyExcel.read(file.getInputStream(),
                RoomDeviceInfoDo.class,
                new RoomDeviceInfoDocListener(brandInfoDoList, deviceTypeDoList, addressInfoDoList, deviceInfoService, userDto.getUserId())).sheet(0).doRead();
        if (RoomDeviceInfoDocListener.message.length() == 0) {
            return R.success();
        } else {
            String message = RoomDeviceInfoDocListener.message.toString();
            RoomDeviceInfoDocListener.message.delete(0,RoomDeviceInfoDocListener.message.length());
            return R.build("A1712", message);
        }

    }

    @GetMapping("/nameList")
    @ApiOperation("查询所有设备名称")
    @ApiOperationSupport(order = 12)
    public R queryNameList() {
        return R.success(deviceInfoService.queryNameList());
    }

    @GetMapping("/list")
    @ApiOperation("分页列表查询")
    @ApiOperationSupport(order = 3)
    @RequiresPermissions("sys:role:list")
    public R pageQuery(@Validated DeviceInfoPageQueryDto dto) {
        return R.success(deviceInfoService.pageQuery(dto));
    }

    @PostMapping("/add")
    @ApiOperation("添加设备")
    @ApiOperationSupport(order = 4)
    public R add(@Validated(AddStrategy.class) @RequestBody DeviceInfoDto dto) {
        return R.build(deviceInfoService.add(dto));
    }

    @PostMapping("/update")
    @ApiOperation("修改设备")
    @ApiOperationSupport(order = 5)
    public R update(@Validated(UpdateStrategy.class) @RequestBody DeviceInfoDto dto) {
        return R.build(deviceInfoService.updateDevice(dto));
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除设备")
    @ApiOperationSupport(order = 6)
    public R delete(@RequestBody String[] ids) {
        return R.build(deviceInfoService.delete(ids));
    }

    @GetMapping("/get/{id}")
    @ApiOperation("查询设备详情")
    @ApiOperationSupport(order = 7)
    public R get(@PathVariable("id") String id) {
        return R.success(deviceInfoService.getDeviceInfo(id));
    }

    @GetMapping("/enquireScrap/{id}")
    @ApiOperation("设备报废询问")
    @ApiOperationSupport(order = 8)
    public R enquireScrap(@PathVariable("id") String id) {
        Boolean flag = DeviceScrapStatus.ONT_SCRAP.getCode();
        DeviceInfoDo deviceInfoDo = deviceInfoService.getById(id);
        //当过期时间小于当前时间，设备直接报废
        if (LocalDateTime.now().isAfter(deviceInfoDo.getExpireTime())) {
            //设备报废
            flag = deviceInfoService.deviceScrap(id);
        }
        return R.success(flag);
    }

    @GetMapping("/deviceScrap/{id}")
    @ApiOperation("设备报废")
    @ApiOperationSupport(order = 9)
    public R deviceScrap(@PathVariable("id") String id) {
        return R.build(deviceInfoService.deviceScrap(id));
    }

    @GetMapping("/queryAddrList")
    @ApiOperation("查询设备地址列表")
    @ApiOperationSupport(order = 10)
    public R queryAddrList(String key) {
        return R.success(addressService.queryAddrList(key));
    }

    @GetMapping("/addrList")
    @ApiOperation("获取设备地址列表")
    @ApiOperationSupport(order = 11)
    public R addrList() {
        List<AddressInfoDo> list = addressService.list();
        List<AddressInfoVo> addrList = new ArrayList<>();
        for (AddressInfoDo addressInfoDo : list) {
            AddressInfoVo addressInfoVo = new AddressInfoVo();
            BeanUtil.copyProperties(addressInfoDo, addressInfoVo);
            addrList.add(addressInfoVo);
        }
        return R.success(addrList);
    }
}
